#!/usr/bin/python

import sys
from alignment import Alignment
from sequence import Sequence
from bucket import Bucket

usage = 'give total 3 args...1st file, 2nd lmer length, 3rd d'

def get_lmers(seq, lmer_len):
    '''Returns all lmers of length lmer_le in seq.'''
    if lmer_len > len(seq):
        raise Exception, 'lmer length is more than sequence length.'
    
    lmers = []
    
    for i in xrange(len(seq)-lmer_len+1):
        lmers.append(seq[i:lmer_len+i])
        
    return lmers

if len(sys.argv) != 4:
    print usage
    sys.exit(1)
l = (int)(sys.argv[2])
d = (int)(sys.argv[3])

file = open(sys.argv[1])
lines = file.readlines()

for i in xrange(len(lines)):
    lines[i] = (lines[i]).strip()
    
# now we need our first l-mer for each bucket

buckets = [] # this will contain all the buckets

# now we would have n-l+1 buckets each having a l-mer from 1st sequence
for lmer in get_lmers(lines[0], l):
    buckets.append(Bucket(lmer))
    
# enrich each bucket with each l-mer from next(2nd) line satisfying 2*d distance criteria
for lmer in get_lmers(lines[1], l):
    for b in buckets:
        if b.qualify(lmer, 2*d):
            if lmer not in b.sequences:
                b.add(lmer)
                
new_bucket = []

for lmer in get_lmers(lines[2], l):
    for b in buckets:
        #flag = False
        for i in xrange(1, len(b.sequences)):
            temp_bucket = Bucket(b.sequences[i])
            if b.qualify(lmer, 2*d) and temp_bucket.qualify(lmer, 2*d):
                #flag = True
                new_bucket.append(Bucket(b.sequences[0]))
                (new_bucket[-1]).add(b.sequences[i])
                (new_bucket[-1]).add(lmer)

                
buckets = new_bucket
del new_bucket
                
        
##for i in xrange(1, len(lines)):
##    line = lines[i]
##    print '*',
##    for lmer in get_lmers(line, l):
##        for b in buckets:
##            if b.qualify(lmer, 2*d):
##                if lmer not in b.sequences:
##                    b.add(lmer)

##print
print len(buckets)
for b in buckets:
    print b.sequences
    #print b.Consensus
    #b.print_freq_matrix()
    #print
    #print len(b.sequences)
    #print b.Consensus#, len(b.sequences), b.sequences